const express = require('express')
const User = require('../Model/User')

const router = express.Router()


router
  .get('/user', (req, res, next) => {
    const filters = req.filter
    // 查找一个
    if (filters.single) {
      User.findOne(filters.filter)
        .populate('creator', { username: 1 })
        .exec((err, doc) => {
          if (err) {
            return res.hasError(500, '服务器错误', err)
          }
          return res.success(doc)
        })
      return
    }
    let total = 0
    User.count((err, doc) => {
      total = parseInt(doc)
    })
    // 查找多个
    User.find(filters.filter, filters.want)
      .limit(filters.pageSize)
      .sort(filters.sort)
      .populate('creator', { username: 1 })
      .populate('tag', { name: 1, _id: -1 })
      .skip((filters.page - 1) * filters.pageSize)
      .exec((err, doc) => {
        if (err) {
          return res.hasError(500, '服务器错误')
        }
        res.success({
          total: total,
          currentPage: filters.page,
          pageSize: filters.pageSize,
          totalPage: Math.ceil(total / filters.pageSize),
          data: doc,
        })
      })
  })
  .get('/user/:userID', (req, res, next) => {
    const user = req.params.userID
    if (!user) {
      res.hasError('参数错误')
    } else {
      User.findById(user)
        .populate('creator', { username: 1 })
        .exec((err, doc) => {
          if (err) {
            res.hasError(500, '服务器错误', err)
          } else {
            res.success(doc)
          }
        })
    }
  })

  // 创建用户
  .post('/user', (req, res, next) => {
    let user = req.body
    console.log(user)
    user.creator = req.user._id
    if (user && user.username && user.code && user.tag.length > 0) {
      User.findOne({ code: user.code }, (err, doc) => {
        if (err) {
          return res.hasError(500, '服务器错误', err)
        }
        if (doc) {
          res.hasError(404, `身份证号已存在：${doc.code},用户名:${doc.username}`)
        } else {
          User.create(user, (err, doc) => {
            if (err) {
              res.hasError(500, '服务器错误', err)
            } else {
              res.success('创建成功', doc)
            }
          })
        }
      })
    } else {
      res.hasError('创建失败:缺少参数')
    }
  })
  .put('/user', (req, res, next) => {

  })
  .delete('/user', (req, res, next) => {

  })

module.exports = router
